<template>
  <div class="personnel-efficiency">
    <div class="page-container">
      <!-- 页面标题和日期筛选 -->
      <div class="page-header">
        <div class="header-content">
          <h1 class="page-title">人员效率统计</h1>
          <div class="date-filter">
            <a-range-picker
              v-model="dateRange"
              format="YYYY-MM-DD"
              :placeholder="['开始日期', '结束日期']"
              @change="onDateRangeChange"
              :allowClear="true"
              style="width: 240px; margin-right: 12px"
            />
            <a-button type="primary" @click="refreshData" :loading="loading">
              <a-icon type="reload" />
              刷新数据
            </a-button>
          </div>
        </div>
      </div>

      <!-- 基础数据卡片 -->
      <div class="data-cards-grid">
        <div class="data-card">
          <a-tooltip placement="top">
            <template slot="title"> 统计系统中参与生产任务的员工总数量 </template>
            <div class="card-title">
              总员工数
              <a-icon type="question-circle" style="color: #999; font-size: 12px; margin-left: 4px" />
            </div>
          </a-tooltip>
          <div class="card-value">
            <span class="value-number">{{ formatNumber(overviewData.totalEmployees) }}</span>
            <span class="value-unit">人</span>
          </div>
        </div>

        <div class="data-card">
          <a-tooltip placement="top">
            <template slot="title"> 所有员工完成的任务总数量 </template>
            <div class="card-title">
              总任务数
              <a-icon type="question-circle" style="color: #999; font-size: 12px; margin-left: 4px" />
            </div>
          </a-tooltip>
          <div class="card-value">
            <span class="value-number">{{ formatNumber(overviewData.totalTasks) }}</span>
            <span class="value-unit">个</span>
          </div>
        </div>

        <div class="data-card">
          <a-tooltip placement="top">
            <template slot="title"> 所有员工的平均效率率，反映整体生产效率水平 </template>
            <div class="card-title">
              平均效率率
              <a-icon type="question-circle" style="color: #999; font-size: 12px; margin-left: 4px" />
            </div>
          </a-tooltip>
          <div class="card-value">
            <span class="value-number" :class="getEfficiencyClass(overviewData.avgEfficiencyRate)">
              {{ formatPercentage(overviewData.avgEfficiencyRate) }}
            </span>
            <span class="value-unit">%</span>
          </div>
        </div>

        <div class="data-card">
          <a-tooltip placement="top">
            <template slot="title"> 整体生产力水平，产量与工时的比值 </template>
            <div class="card-title">
              整体生产力
              <a-icon type="question-circle" style="color: #999; font-size: 12px; margin-left: 4px" />
            </div>
          </a-tooltip>
          <div class="card-value">
            <span class="value-number">{{ formatNumber(overviewData.overallProductivity) }}</span>
            <span class="value-unit">件/时</span>
          </div>
        </div>
      </div>

      <!-- 图表区域 -->
      <div class="charts-container">
        <!-- 员工产量排行榜 -->
        <div class="chart-card full-width">
          <div class="chart-header">
            <h3 class="chart-title">员工产量排行榜</h3>
            <div class="chart-controls">
              <a-select v-model="productionRankingLimit" @change="updateProductionRanking" style="width: 120px">
                <a-select-option value="5">TOP 5</a-select-option>
                <a-select-option value="10">TOP 10</a-select-option>
                <a-select-option value="20">TOP 20</a-select-option>
              </a-select>
            </div>
          </div>
          <div class="chart-content">
            <div ref="productionRankingChart" class="chart"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getAction } from '@/api/manage'
import * as XLSX from 'xlsx'

export default {
  name: 'PersonnelEfficiency',
  data() {
    return {
      loading: false,
      exportLoading: false,
      dateRange: [],
      productionRankingLimit: '10',

      // 概览数据
      overviewData: {
        totalEmployees: 0,
        totalTasks: 0,
        avgEfficiencyRate: 0,
        overallProductivity: 0,
      },

      // 图表实例
      charts: {},

      // 图表数据
      chartData: {
        employeeRanking: [],
      },
    }
  },

  mounted() {
    this.initCharts()
    this.loadData()
  },

  beforeDestroy() {
    // 销毁图表实例
    Object.values(this.charts).forEach((chart) => {
      if (chart) {
        chart.dispose()
      }
    })
  },

  methods: {
    initCharts() {
      this.$nextTick(() => {
        this.charts.productionRanking = echarts.init(this.$refs.productionRankingChart)

        // 监听窗口大小变化
        window.addEventListener('resize', this.handleResize)
      })
    },

    handleResize() {
      Object.values(this.charts).forEach((chart) => {
        if (chart) {
          chart.resize()
        }
      })
    },

    async loadData() {
      this.loading = true
      try {
        await Promise.all([this.loadOverviewData(), this.loadProductionRanking()])
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('加载数据失败')
      } finally {
        this.loading = false
      }
    },

    async loadOverviewData() {
      const params = this.getDateParams()
      const res = await getAction('/mes/statistics/personnel/efficiency/overview', params)
      if (res.success && res.result) {
        this.overviewData = {
          totalEmployees: res.result.total_employees || 0,
          totalTasks: res.result.total_tasks || 0,
          avgEfficiencyRate: res.result.avg_efficiency_rate || 0,
          overallProductivity: res.result.overall_productivity || 0,
        }
      }
    },

    async loadProductionRanking() {
      const params = {
        ...this.getDateParams(),
        limit: parseInt(this.productionRankingLimit),
      }
      const res = await getAction('/mes/statistics/personnel/efficiency/production-ranking', params)
      if (res.success && res.result) {
        this.updateProductionRankingChart(res.result)
      }
    },

    updateProductionRankingChart(data) {
      const employees = data.map((item) => item.employee_name || '未知员工')
      const production = data.map((item) => item.total_production || 0)
      const efficiency = data.map((item) => item.completion_rate || 0)

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
          },
        },
        legend: {
          data: ['总产量', '完成率'],
        },
        xAxis: {
          type: 'category',
          data: employees,
          axisLabel: {
            rotate: 45,
          },
        },
        yAxis: [
          {
            type: 'value',
            name: '产量',
            position: 'left',
          },
          {
            type: 'value',
            name: '完成率 (%)',
            position: 'right',
            max: 100,
          },
        ],
        series: [
          {
            name: '总产量',
            type: 'bar',
            yAxisIndex: 0,
            data: production,
            itemStyle: {
              color: '#1890ff',
            },
          },
          {
            name: '完成率',
            type: 'line',
            yAxisIndex: 1,
            data: efficiency,
            itemStyle: {
              color: '#52c41a',
            },
            lineStyle: {
              width: 2,
            },
          },
        ],
      }

      this.charts.productionRanking.setOption(option)
    },

    async updateProductionRanking() {
      await this.loadProductionRanking()
    },

    onDateRangeChange() {
      this.loadData()
    },

    refreshData() {
      this.loadData()
    },

    getDateParams() {
      const params = {}
      if (this.dateRange && this.dateRange.length === 2) {
        params.startDate = this.dateRange[0].format('YYYY-MM-DD')
        params.endDate = this.dateRange[1].format('YYYY-MM-DD')
      }
      return params
    },

    formatNumber(value) {
      if (value === null || value === undefined) return '0'
      return Number(value).toLocaleString()
    },

    formatPercentage(value) {
      if (value === null || value === undefined) return '0.00'
      return Number(value).toFixed(2)
    },

    getEfficiencyClass(value) {
      if (value >= 100) return 'efficiency-high'
      if (value >= 80) return 'efficiency-medium'
      return 'efficiency-low'
    },

    async exportData() {
      this.exportLoading = true
      try {
        const params = this.getDateParams()

        // 导出所有统计数据
        const exportData = {
          概览数据: this.overviewData,
          员工产量排行: this.chartData.employeeRanking,
        }

        // 创建Excel数据
        const wb = XLSX.utils.book_new()

        // 概览数据工作表
        const overviewWs = XLSX.utils.json_to_sheet([this.overviewData])
        XLSX.utils.book_append_sheet(wb, overviewWs, '概览数据')

        // 员工产量排行工作表
        if (this.chartData.employeeRanking.length > 0) {
          const rankingWs = XLSX.utils.json_to_sheet(this.chartData.employeeRanking)
          XLSX.utils.book_append_sheet(wb, rankingWs, '员工产量排行')
        }

        // 生成文件名
        const fileName = `人员效率统计_${new Date().toISOString().slice(0, 10)}.xlsx`

        // 下载文件
        XLSX.writeFile(wb, fileName)

        this.$message.success('数据导出成功')
      } catch (error) {
        console.error('导出失败:', error)
        this.$message.error('数据导出失败')
      } finally {
        this.exportLoading = false
      }
    },
  },
}
</script>

<style lang="less" scoped>
.personnel-efficiency {
  background: #f5f7fa;
  min-height: 100vh;
  padding: 16px;
}

.page-container {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.date-filter {
  display: flex;
  align-items: center;
}

.data-cards-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin-bottom: 16px;
}

.data-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  }
}

.card-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}

.card-value {
  display: flex;
  align-items: baseline;
}

.value-number {
  font-size: 24px;
  font-weight: 600;
  color: #303133;

  &.efficiency-high {
    color: #67c23a;
  }

  &.efficiency-medium {
    color: #e6a23c;
  }

  &.efficiency-low {
    color: #f56c6c;
  }
}

.value-unit {
  font-size: 12px;
  color: #606266;
  margin-left: 4px;
}

.charts-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.full-width {
  width: 100%;
}

.chart-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.chart-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.chart-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  padding: 24px 32px;
  margin-bottom: 24px;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.15);

  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .page-title {
      font-size: 28px;
      font-weight: 600;
      color: #ffffff;
      margin: 0;
      text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    .date-filter {
      display: flex;
      align-items: center;
      gap: 12px;

      .ant-btn-primary {
        background: rgba(255, 255, 255, 0.2);
        border: 1px solid rgba(255, 255, 255, 0.3);
        border-radius: 8px;
        font-weight: 500;
        backdrop-filter: blur(10px);
        transition: all 0.3s ease;

        &:hover {
          background: rgba(255, 255, 255, 0.3);
          border-color: rgba(255, 255, 255, 0.5);
          transform: translateY(-1px);
        }
      }

      .ant-btn:not(.ant-btn-primary) {
        background: rgba(255, 255, 255, 0.1);
        border: 1px solid rgba(255, 255, 255, 0.2);
        border-radius: 8px;
        color: #ffffff;
        font-weight: 500;
        backdrop-filter: blur(10px);
        transition: all 0.3s ease;

        &:hover {
          background: rgba(255, 255, 255, 0.2);
          border-color: rgba(255, 255, 255, 0.4);
          color: #ffffff;
          transform: translateY(-1px);
        }
      }

      .ant-calendar-picker {
        .ant-calendar-picker-input {
          background: rgba(255, 255, 255, 0.9);
          border: 1px solid rgba(255, 255, 255, 0.3);
          border-radius: 8px;
          backdrop-filter: blur(10px);

          &:hover {
            border-color: rgba(255, 255, 255, 0.5);
          }
        }
      }
    }
  }
}

.chart-content {
  height: 300px;
}

.chart {
  width: 100%;
  height: 100%;
}

@media (max-width: 1200px) {
  .data-cards-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .data-cards-grid {
    grid-template-columns: 1fr;
  }

  .page-header .header-content {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
}
</style>
